package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Builder
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */

    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常(地址簿为空，购物车数据为空)
        //判断当前用户是否有填写地址
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {//地址为空
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断用户是否有选购商品
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)//设置用户id
                .build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);//查询当前用户购物车数据
        if (list == null || list.size() == 0) {//购物车为空
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //1.向订单表插入一条数据
        //首先应构造一个订单对象
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);//将ordersSubmitDTO对象中的属性复制到orders对象中
        orders.setOrderTime(LocalDateTime.now());//设置下单时间
        orders.setPayStatus(Orders.UN_PAID);//未支付
        orders.setStatus(Orders.PENDING_PAYMENT);//待付款
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//将时间戳作为订单号
        orders.setPhone(addressBook.getPhone());//设置手机号
        orders.setUserId(userId);//设置用户id
        orders.setAddress(addressBook.getDetail());//设置地址
        orders.setConsignee(addressBook.getConsignee());//设置收货人

        orderMapper.insert(orders);
        //2.向订单明细表插入多条数据
        List<OrderDetail>  orderDetails = new ArrayList<>();
        for(ShoppingCart cart : list){
            OrderDetail orderDetail = new OrderDetail();//构造一个订单明细对象
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());//设置 订单明细  中的  订单id
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);//批量插入订单明细数据
        //3.清空用户当前的购物车数据
        shoppingCartMapper.deleteById(userId);
        //4.返回OrderSubmitVO对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())//设置订单id
                .orderNumber(orders.getNumber())//设置订单号
                .orderAmount(orders.getAmount())//设置订单总金额
                .orderTime(orders.getOrderTime())//设置下单时间
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

        //正常情况下须删除
        String orderNumber = ordersPaymentDTO.getOrderNumber();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");//订单已支付

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            paySuccess(orderNumber);//正常情况下须删除
            throw new OrderBusinessException("该订单已支付");

        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type",1); //1.表示来单提醒 2.表示客户催单
        map.put("orderId",orders.getId());//订单id
        map.put("content",outTradeNo);//订单号
        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);//将消息推送到 客户端浏览器
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //首先查询订单的数据
        Long userId = BaseContext.getCurrentId();//获取当前用户id
        ordersPageQueryDTO.setUserId(userId);//设置用户id
        //分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> records = page.getResult();
        long total = page.getTotal();
        //其次查询订单明细的数据
        List<OrdersVOPlus> ordersVOPluses = new ArrayList<>();
        for (Orders orders : records) { //遍历订单数据
            OrdersVOPlus ordersVOPlus = new OrdersVOPlus();
            BeanUtils.copyProperties(orders, ordersVOPlus);
            //将订单id查询订单明细数据
            Long ordersId = orders.getId();
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);
            ordersVOPlus.setOrderDetailList(orderDetailList);

            //添加到集合中
            ordersVOPluses.add(ordersVOPlus);
        }
        return new PageResult(total, ordersVOPluses);
    }
    /**
     * 查询订单详情
     * @param orderId
     * @return
     */
    @Override
    public OrdersVOPlus getOrderDetails(Long orderId) {
        OrdersVOPlus ordersVOPlus = new OrdersVOPlus();
        //查询订单数据
        OrderVO orderVO = orderMapper.selectById(orderId);
        BeanUtils.copyProperties(orderVO, ordersVOPlus);
        //获取订单明细数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
        ordersVOPlus.setOrderDetailList(orderDetailList);
        return ordersVOPlus;
    }
    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Integer status = Orders.CANCELLED;//将状态改为已取消
        //将取消原因设置为用户取消
        OrdersCancelDTO ordersCancelDTO = new OrdersCancelDTO();
        ordersCancelDTO.setId(id);
        ordersCancelDTO.setCancelReason("顾客取消");
        //设置取消时间为当前时间
        orderMapper.updateById(status, ordersCancelDTO , LocalDateTime.now());
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //获取其的订单明细数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //将订单明细数据添加到购物车
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO statistics() {
        Long userId = BaseContext.getCurrentId();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        Integer count = orderMapper.statusCount(Orders.TO_BE_CONFIRMED);//待派送
        orderStatisticsVO.setToBeConfirmed(count);//设置待派送
        count = orderMapper.statusCount(Orders.CONFIRMED);//已派送
        orderStatisticsVO.setConfirmed(count);
        count = orderMapper.statusCount(Orders.DELIVERY_IN_PROGRESS);//已接单
        orderStatisticsVO.setDeliveryInProgress(count);
        return orderStatisticsVO;
    }
    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult ScanpageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        List<OrdersScanVO> ordersScanVOS = new ArrayList<>();
        //分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> records = page.getResult();
        long total = page.getTotal();
        //查询菜单明细，将菜品名称拼接
        for (Orders orders : records){
            OrdersScanVO ordersScanVO = new OrdersScanVO();
            //获取订单id
            Long ordersId = orders.getId();

            BeanUtils.copyProperties(orders,ordersScanVO);
            StringBuilder stringBuilder = new StringBuilder();//创建一个可变字符串
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);
            for (OrderDetail orderDetail : orderDetailList) {
                    stringBuilder.append(orderDetail.getName()+" ");
            }
            String dishNames = stringBuilder.toString();
            ordersScanVO.setOrderDishes(dishNames);
            ordersScanVOS.add(ordersScanVO);
        }
        return new PageResult(total,ordersScanVOS);
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        orderMapper.confirmOrders(ordersConfirmDTO);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.rejectionOrders(ordersRejectionDTO);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Integer status = Orders.CANCELLED;
        orderMapper.adminCancel(ordersCancelDTO ,status,LocalDateTime.now());
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Integer deliveryInProgress = Orders.DELIVERY_IN_PROGRESS;
        orderMapper.delivery(id,deliveryInProgress);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void adminComplete(Long id) {
        Integer status = Orders.COMPLETED;
        orderMapper.complete(id,status);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //查询订单
        Orders orders = orderMapper.selectById(id);

        //校验订单是否存在
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("type",2);
        map.put("OrderId",id);
        map.put("content",orders.getNumber());
        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

}
